/*
 * SDLIntroSection.cpp
 *
 *  Created on: Nov 24, 2009
 *      Author: uauser
 */

#include <iostream>
#include <SDL.h>
#include <cmath>
#include <fstream>
#include "SDLIntroSection.h"
#include "SDLImageRepresentation.h"
#include "SDLRectangleRepresentation.h"
#include "SDLZoomDrawer.h"
#include "SDLTimer.h"
#include "linearController.h"



namespace si_sdl {

SDLIntroSection::SDLIntroSection(
		SDLApplication& parent,
		SDLWindow& win):
	SDLApplicationSection(parent, win)

{
	std::ifstream fileIn("config/introtext.txt");
	if(fileIn.bad())
		throw SDLException("Cannot find config/introtext.txt");

	std::string text;
	std::getline(fileIn, text, char(0));

	std::tr1::shared_ptr<si::Representation> rep(
							new SDLTextRepresentation(
								text,
								"fonts/Vera.ttf",
								20,
								Color(255,0,0),
								Color(0,0,0),
								ALIGN_CENTER));


	const double vSpeed = -15.0;
	std::tr1::shared_ptr<si::Controller> textController = std::tr1::shared_ptr<si::Controller>(
							new si::LinearController(
									// this text will center itself
									si::Vector2(0, SDLZoomDrawer::get()->requestDrawableRegion().getY()),
									si::Vector2(0, vSpeed),// vertical speed
									si::Vector2(8.0,6.0)) // size
									);

	fTextObj = std::tr1::shared_ptr<SDLMovingText>(new SDLMovingText(rep, textController));

	//calculate how long it will take for the text to pass by
	// this is based on time it takes for the length of text + half of the screen to pass by
	fEndTime = (rep->getSize().getY()+SDLZoomDrawer::get()->requestDrawableRegion().getY()/2)/fabs(vSpeed);

}

SDLIntroSection::~SDLIntroSection() {
	// TODO Auto-generated destructor stub
}
void SDLIntroSection::newFrame(double timeSinceLastFrame)
{
	// Do we need to change sections?
	static SDLTimer timer;

	if(timer.poll() > fEndTime)
		fParent.changeSectionTo(si::MENU);

	// draw text
	SDLRectangleRepresentation::drawRect(
			si::Vector2(0,0),
			SDLZoomDrawer::get()->requestDrawableRegion(),
			Color(0,0,0));
	fTextObj->update(timeSinceLastFrame);
	fTextObj->draw();
	// move background up by 10 px / sec

}

void SDLIntroSection::onSDLEvent(SDL_Event & event)
{
	SDLApplicationSection::onSDLEvent(event); // make sure SDL_QUIT's are caught...

	// When user presses space goto menu
	if(event.type == SDL_KEYDOWN)
		if(event.key.keysym.sym == SDLK_SPACE || event.key.keysym.sym == SDLK_ESCAPE)
			fParent.changeSectionTo(si::MENU);


}

}
